﻿using System;
using System.Diagnostics;
using RayDen.Library.Components.Surface;
using RayDen.Library.Core;
using RayDen.Library.Core.Primitives;
using RayDen.RayEngine.Core.Interface;
using RayDen.RayEngine.Core.Types;
using RayDen.RayEngine.Engines.PathTracer;
using RayDen.RayEngine.Samplers;

namespace RayDen.RayEngine.Engines.LightTracer
{

    public class LightTracerPathSampler : PathSamplerBase
    {
        private int MaxEyeRays = 1;
        internal RgbSpectrum Throughput;
        public PathTracerPathState PathState;



        protected int depth, tracedShadowRayCount;
        protected float pathWeight;
        protected bool specularBounce;

        public UInt64 PathExpression;

        protected RayEngineScene scene;
        private ConnectRayInfo[] secRays;
        SurfaceIntersectionData hitInfo = null;
        public int MaxRaysPerPath
        {
            get;
            set;
        }

        internal struct ConnectRayInfo
        {
            public float pdf;
            public RgbSpectrum color;
            public RayData shadowRay;
            public int currentShadowRayIndex;
        }



        public override void InitPath(IPathProcessor buffer)
        {
            base.InitPath(buffer);
            this.scene = pathIntegrator.Scene;
            this.PathState = PathTracerPathState.EyeVertex;
            if (this.secRays == null)
                this.secRays = new ConnectRayInfo[MaxEyeRays];
            this.RayIndex = -1;
            this.pathWeight = 1.0f;
            this.tracedShadowRayCount = 0;
            this.depth = 0;
            this.specularBounce = true;
            this.Radiance = new RgbSpectrum(0f);

            this.Sample = pathIntegrator.Sampler.GetSample(null);
            LightSample ls;
            var light = scene.Lights[scene.SampleLights(Sample.GetLazyValue())];
            light.EvaluatePhoton(scene, Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), out ls);
            PathRay = ls.LightRay;
            var lightPdf = ls.Pdf;
            Throughput = (RgbSpectrum)(ls.Spectrum);
            //* scene.Lights.Length) / lightPdf;

            //buffer.Scene.Camera.GetRay(Sample.imageX, Sample.imageY, out this.PathRay);
        }
        public override void Splat(SampleBuffer sampleBuffer)
        {
#if VERBOSE
            this.pathIntegrator.splattedCount++;
#endif
            this.InitPath(pathIntegrator);
        }

        private void Splat(SampleBuffer smb, float x, float y, ref RgbSpectrum rad)
        {
            if (x < 0 || y < 0)
                return;
            if (x > 1280 || y > 720)
                return;
            smb.SplatSample(x, y, ref rad);
        }


        public override bool FillRayBuffer(RayBuffer rayBuffer)
        {
            var leftSpace = rayBuffer.LeftSpace();
            if (((PathState == PathTracerPathState.EyeVertex) && (1 > leftSpace)) ||
            ((PathState == PathTracerPathState.ShadowRaysOnly) && (tracedShadowRayCount > leftSpace)) ||
            ((PathState == PathTracerPathState.NextVertex) && (tracedShadowRayCount + 1 > leftSpace)))
                return false;
            if (PathState != PathTracerPathState.ShadowRaysOnly)
                RayIndex = rayBuffer.AddRay(ref PathRay);
            if (PathState == PathTracerPathState.NextVertex || PathState == PathTracerPathState.ShadowRaysOnly)
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                    secRays[i].currentShadowRayIndex = rayBuffer.AddRay(ref secRays[i].shadowRay);
            }
            return true;
        }


        private void AddEyeRay(ref Point hp, ref Vector wo, ref RgbSpectrum lightTroughtput, float lpdf)
        {
            RayData eyeRay;
            float eyePdf = 1f;


            scene.Camera.Sample(ref hp, ref hitInfo.Normal, ref hitInfo.ShadingNormal, Sample.GetLazyValue(), Sample.GetLazyValue(), Sample.GetLazyValue(), out eyeRay, out eyePdf);

            secRays[tracedShadowRayCount].color = RgbSpectrum.UnitSpectrum();
            secRays[tracedShadowRayCount].pdf = eyePdf;
            secRays[tracedShadowRayCount].shadowRay = eyeRay;
            Vector lwi = eyeRay.Dir;

            RgbSpectrum fs;
            hitInfo.MMaterial.f(
                ref secRays[tracedShadowRayCount].shadowRay.Dir,
                ref wo, ref hitInfo.ShadingNormal, ref Throughput, out fs, types: BrdfType.Diffuse);
            secRays[tracedShadowRayCount].color *= lightTroughtput *
                                                   Vector.AbsDot(ref hitInfo.Normal, ref lwi) * fs;
            if (!secRays[tracedShadowRayCount].color.IsBlack())
            {
                secRays[tracedShadowRayCount].pdf /= lpdf;
                tracedShadowRayCount++;
            }
        }

        public override void Advance(RayBuffer rayBuffer, SampleBuffer consumer)
        {
            int currentTriangleIndex = 0;
#if VERBOSE

            try {
#endif

            base.Advance(rayBuffer, consumer);

            RayHit rayHit = rayBuffer.rayHits[RayIndex];

            if (((PathState == PathTracerPathState.ShadowRaysOnly) || (PathState == PathTracerPathState.NextVertex)) &&
                (tracedShadowRayCount > 0))
            {
                for (int i = 0; i < tracedShadowRayCount; ++i)
                {
                    RayHit shadowRayHit = rayBuffer.rayHits[secRays[i].currentShadowRayIndex];
                    RgbSpectrum attenuation;
                    bool continueTrace;
                    if (this.ShadowRayTest(ref shadowRayHit, ref secRays[i].shadowRay, out attenuation, out continueTrace))
                    {
                        //                            Radiance.MADD()
                        Radiance += ((secRays[i].color) / secRays[i].pdf);
                        pathWeight *= secRays[i].pdf;
                        var d = secRays[i].shadowRay.Point(shadowRayHit.Distance);
                        var pix = scene.Camera.UnProject(ref d);
                        this.Splat(consumer, pix.x, 720f - pix.y, ref Radiance );
                    }
                }

                if (PathState == PathTracerPathState.ShadowRaysOnly)
                {
                    Splat(consumer);
                    return;
                }
                tracedShadowRayCount = 0;

            }

            depth++;
            bool missed = rayHit.Index == 0xffffffffu;
            if (missed || PathState == PathTracerPathState.ShadowRaysOnly || depth > scene.MaxPathDepth)
            {
                if (missed)
                {
                    RgbSpectrum env;
                    this.SampleEnvironment(ref PathRay.Dir, out env);
                    Radiance += env * Throughput;
                }
                Splat(consumer);

                return;
            }

            // Something was hit
            if (hitInfo == null)
            {
                hitInfo = SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, IntersectionOptions.ResolveObject);
            }
            else
            {
                SurfaceSampler.GetIntersection(ref PathRay, ref rayHit, ref hitInfo, IntersectionOptions.ResolveObject);
            }
            currentTriangleIndex = (int)rayHit.Index;

            if (hitInfo == null)
            {
                Debugger.Break();
            }
            Vector wo = -PathRay.Dir;
            var hitPoint = PathRay.Point(rayHit.Distance);

            //If Hit light)
            if (hitInfo.IsLight)
            {
                //if (specularBounce || depth == 1)
                {
                    var lt = scene.GetLightByIndex(currentTriangleIndex);
                    if (lt != null)
                    {
                        var le = (RgbSpectrum)(lt.Le(ref wo));
                        Throughput *= le;
                        AddEyeRay(ref hitPoint, ref wo, ref Throughput, 1f);
                        PathState = PathTracerPathState.ShadowRaysOnly;
                        return;
                    }
                }
           }


            var bsdf = hitInfo.MMaterial;

            if (bsdf.IsDiffuse())
            {
                float lightStrategyPdf = 1f;
                //scene.ShadowRaysPerSample/(float)scene.Lights.Length;
                var lightTroughtput = Throughput*hitInfo.Color;

                AddEyeRay(ref hitPoint, ref wo, ref lightTroughtput, lightStrategyPdf );

           }

            float fPdf = 0f;
            var wi = new Vector();
            RgbSpectrum f;
     
            f = bsdf.Sample_f(ref wo, out wi, ref hitInfo.Normal, ref hitInfo.ShadingNormal, ref Throughput,
                                Sample.GetLazyValue(), Sample.GetLazyValue(),
                                Sample.GetLazyValue(), ref hitInfo.TextureData,
                                out fPdf, out specularBounce)*hitInfo.Color;

            if ((fPdf <= 0.0f) || f.IsBlack())
            {
                if (tracedShadowRayCount > 0)
                    PathState = PathTracerPathState.ShadowRaysOnly;
                else
                {
                    Splat(consumer);

                }
                return;
            }
            pathWeight *= fPdf;
            Throughput *= f / fPdf;

            if (depth > scene.MaxPathDepth)
            {
                float prob = Math.Max(Throughput.Filter(), scene.RussianRuletteImportanceCap);
                if (prob >= Sample.GetLazyValue())
                {
                    Throughput /= prob;
                    pathWeight *= prob;
                }
                else
                {
                    if (tracedShadowRayCount > 0)
                        PathState = PathTracerPathState.ShadowRaysOnly;
                    else
                    {
                        Splat(consumer);

                    }

                    return;
                }
            }

            PathRay.Org = hitPoint;
            PathRay.Dir = wi.Normalize();
            PathState = PathTracerPathState.NextVertex;

#if VERBOSE
            }
            catch (Exception ex) {
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Advance path exception");
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine("Error triangle {0}", currentTriangleIndex);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.Message);
                RayDen.Library.Components.SystemComponents.Tracer.TraceLine(ex.StackTrace);

            }
#endif
        }

        protected override bool ShadowRayTest(ref RayHit shadowRayHit, ref RayData shadowRay, out RgbSpectrum attenuation, out bool continueTrace)
        {
            var hit = shadowRayHit.Index == 0xffffffffu || scene.IsLight((int)shadowRayHit.Index);
            attenuation = new RgbSpectrum(1f);
            continueTrace = false;

            return hit;
        }

        private void SampleEnvironment(ref Vector vector, out RgbSpectrum result)
        {
            result = this.LightSampler.SampleEnvironment(vector);
        }

    }
}
